package com.lsh.ofc.worker.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.exception.BusinessException;
import com.lsh.ofc.core.constant.Constants;
import com.lsh.ofc.core.entity.OfcObdDetail;
import com.lsh.ofc.core.entity.OfcObdHead;
import com.lsh.ofc.core.entity.OfcTask;
import com.lsh.ofc.core.enums.OfcTaskStatus;
import com.lsh.ofc.core.enums.OfcTaskType;
import com.lsh.ofc.core.proxy.service.WumartBasicService;
import com.lsh.ofc.core.redis.RedisTemplate;
import com.lsh.ofc.core.service.OfcObdService;
import com.lsh.ofc.core.service.OfcTaskService;
import com.lsh.ofc.core.util.DateUtil;
import com.lsh.ofc.proxy.context.WumartBasicContext;
import com.lsh.ofc.proxy.model.CreateWgPoTransferReqDetail;
import com.lsh.ofc.proxy.model.CreateWgPoTransferReqHead;
import com.lsh.ofc.proxy.service.WgServiceProxy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * 创建SO任务
 *
 * @author peter
 * @date 19/3/29
 */
@Component
@Slf4j
public class OfcObd2PoJob extends AbstractOfcTaskJob {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OfcTaskService ofcTaskService;

    @Autowired
    private OfcObdService ofcObdService;

    @Autowired
    private WgServiceProxy wgServiceProxy;

    @Autowired
    private WumartBasicService wumartBasicService;


    @Override
    protected OfcTaskType getFetchTaskType() {
        return OfcTaskType.OBD_PO_PSI;
    }

    /**
     * 包含 DC10 汇总so的 obd 的po 过账
     *
     * @param task
     * @return
     * @throws BusinessException
     */
    @Override
    protected int processTask(OfcTask task) throws BusinessException {
        boolean ret;
        Map<String, Integer> venderIdMap = new HashMap<>();
        venderIdMap.put("SAAS3", 20059);
        venderIdMap.put("SAAS1", 1216);
        venderIdMap.put("SAAS20169",100400);

        try {
            Long orderCode = task.getRefId();

            OfcObdHead filter = new OfcObdHead();
            filter.setOrderCode(orderCode);
            List<OfcObdHead> obdHeadList = ofcObdService.findList(filter, true);
            if (CollectionUtils.isEmpty(obdHeadList)) {
                log.info("SO单不存在，订单号：{}", orderCode);
                return 0;
            }

            for (OfcObdHead ofcObdHead : obdHeadList) {

                String ownerId = this.wumartBasicService.getOwnerId(WumartBasicContext.buildContext(ofcObdHead.getRegionCode(), ofcObdHead.getSupplierCode(), ofcObdHead.getSupplierOrg(), ofcObdHead.getSupplierId(),ofcObdHead.getSupplierGroup()));
                String wgPath = this.wumartBasicService.getWmsPath(WumartBasicContext.buildContext(ofcObdHead.getRegionCode(), ofcObdHead.getSupplierCode(), ofcObdHead.getSupplierOrg(), ofcObdHead.getSupplierId(),ofcObdHead.getSupplierGroup()));
                String sourceDC = this.wumartBasicService.getSourceDC(WumartBasicContext.buildContext(ofcObdHead.getRegionCode(), ofcObdHead.getSupplierCode(), ofcObdHead.getSupplierOrg(), ofcObdHead.getSupplierId(),ofcObdHead.getSupplierGroup()));

                CreateWgPoTransferReqHead poOrder = new CreateWgPoTransferReqHead();
                poOrder.setWarehouseCode(sourceDC);
                poOrder.setOwnerId(Integer.valueOf(ownerId));
                poOrder.setWmPoId(ofcObdHead.getSoCode());
                poOrder.setWmSoId(ofcObdHead.getSoBillCode());
                poOrder.setReceiveDate(DateUtil.defaultTime(new Date()));
                poOrder.setRecordId(ofcObdHead.getSoBillCode());
                poOrder.setIsSyncLsh(1);
                poOrder.setVenderId(venderIdMap.get(ofcObdHead.getSupplierCode()));
                poOrder.setMisVenderId(ofcObdHead.getVenderId());

                poOrder.setSupplierName(ofcObdHead.getSupplierCode() + "-" + ofcObdHead.getSupplierDc());

                List<CreateWgPoTransferReqDetail> details = new ArrayList<>();
//                Integer lineNo = 10;
                for (OfcObdDetail obdDetail : ofcObdHead.getDetails()) {
                    CreateWgPoTransferReqDetail reqDetail = new CreateWgPoTransferReqDetail();
                    reqDetail.setGoodsId(obdDetail.getSkuSupplyCode());
                    reqDetail.setLineNo(obdDetail.getItemCode());
//                    lineNo += 10;
                    reqDetail.setQty(obdDetail.getSkuDeliverQty());

                    JSONObject deExt = JSON.parseObject(obdDetail.getExt());
                    String priceStr = deExt.getString(Constants.OFC_SO_WUMART_CALLBACK_SUPPLY_PRICE);

                    if (StringUtils.isBlank(priceStr)) {
                        logger.info(obdDetail.getSkuSupplyCode() +" : 价格不存在 ");
                        return -1;
                    }
                    BigDecimal price = new BigDecimal(priceStr);
                    reqDetail.setPrice(price);
                    reqDetail.setPackUnit(1);

                    details.add(reqDetail);
                }

                poOrder.setDetails(details);
                String poId = wgServiceProxy.sendPoAndTransfer(poOrder, wgPath);
                //po 请求经销存 成功 TODO 不再有DC12 DC15 等物美仓库
//                if (StringUtils.isNotBlank(poId) && !dc.equals("DC10")) {
//                    OfcTask taskPsi = new OfcTask();
//                    taskPsi.setRefId(orderCode);
//                    taskPsi.setType(OfcTaskType.OBD_SO_PSI.getValue());
//                    taskPsi.setStatus(OfcTaskStatus.NEW.getValue());
//
//                    if (this.ofcTaskService.countTask(taskPsi) <= 0 && redisTemplate.lock(MessageFormat.format(Constants.OFC_OBD_PSI_LOCK, orderCode), 10)) {
//                        taskPsi.setContent(orderCode.toString());
//                        this.ofcTaskService.addTask(taskPsi);
//                    }
//                }
            }

            ret = true;
        } catch (BusinessException e) {
            logger.error("请求进销存，创建PO，并直接过账 任务处理失败", e);
            ret = false;
        }

        return ret == true ? 1 : -1;
    }


    @Override
    protected boolean filterFlag(OfcTask task) {

        return false;
    }

    @Override
    protected List<OfcTask> fetchTasks(OfcTaskType type, Set<OfcTaskStatus> statuses, int shardingCount, List<Integer> shardingItems, int fetchSize) {
        return super.defaultFetchTasks(type, statuses, shardingCount, shardingItems, fetchSize);
    }
}
